<?php

class DrugController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    protected $idStore = 3;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('view', 'index', 'indexByTypes'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete', 'update'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $model = $this->loadModel($id);
        $prices = Drugstore::model()->findByAttributes(array('id_drug'=>$id));
        $comment = $this->createComment($model);
        $visit =Drug::model()->findByPk($id);
        $visit->updateCounters(
            array('userview'=>1),"id={$id}"   
        );
        $this->render('view', array(
            'model' => $model,
            'prices' => $prices,
            'comment' => $comment,
            'visit'=>$visit,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Drug;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Drug'])) {
            $model->attributes = $_POST['Drug'];
            $model->images = CUploadedFile::getInstance($model, 'images');
            if (isset($_POST['Drug']["radio"])) {
                if ($_POST['Drug']["radio"] == 0) {
                    $model->check = 1;
                } else {
                    $model->check = 2;
                }
                $model->idStore = $_POST['Drug']["idStore"];
            }
            if (isset($_POST['Drug']["hidden"])) {
                if ($_POST['Drug']["hidden"] == -2) {
                    if ($_POST['Drug']["nameStore"] == "" || $_POST['Drug']["addressStore"] == "") {
                        if ($_POST['Drug']["nameStore"] != "") {
                            $model->addError('addressStore', 'Bạn chưa nhập địa chỉ cửa hàng');
                        } else if ($_POST['Drug']["addressStore"] != "") {
                            $model->addError('nameStore', 'Bạn chưa nhập tên cửa hàng');
                        } else {
                            $model->addError('nameStore', 'Bạn chưa nhập tên cửa hàng');
                            $model->addError('addressStore', 'Bạn chưa nhập địa chỉ cửa hàng');
                        }
                        $model->check = 1;
                    } else {
                        $sqlStore = "insert into tbl_store(name,address) values ('" . $_POST['Drug']["nameStore"] . "','" . $_POST['Drug']["addressStore"] . "')";
                        Yii::app()->db->createCommand($sqlStore)->execute();
                        $arrStore = Yii::app()->db->createCommand("select id_store from tbl_store order by id_store desc limit 1")->queryRow();
                        $model->idStore = $arrStore["id_store"];
                        $model->check = 2;
                        Yii::app()->user->setFlash('_form','Thank you for contacting us. We will respond to you as soon as possible.');
                    }
                }
                if ($_POST['Drug']["hidden"] != -2) {
                    if ($model->save()) {
                        $idDrug = Yii::app()->db->createCommand("select id from tbl_drug order by id desc limit 1")->queryRow();
                        $sqlDrugStore = "insert into tbl_drugstore(id_store,id_drug,price,time_add) values ('" . $_POST['Drug']["hidden"]. "','" . $idDrug["id"] . "','" . $_POST['Drug']["priceDrug"] . "',NOW())";
                        Yii::app()->db->createCommand($sqlDrugStore)->execute();
                        $path = Yii::getPathOfAlias('webroot') . '/data/images/';
                        $model->images->saveAs($path . $model->images);
                        $this->redirect(array('view', 'id' => $model->id));
                    }else{
                        $model->check = 2;
                    }
                }
            }
        }
        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Drug'])) {
            $model->attributes = $_POST['Drug'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $model = Typedrug::model()->findAll();
        $this->render('index', array('model'=>$model));
    }
    
    public function actionIndexByTypes($id_type) {
        $model = Drug::model()->findAllByAttributes(array('id_type'=>$id_type));
        $this->render('indexByTypes', array('model'=>$model));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Drug('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Drug']))
            $model->attributes = $_GET['Drug'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Drug::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'drug-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    protected function createComment($issue) {
        $comment = new Comment;
        if (isset($_POST['Comment'])) {
            $comment->attributes = $_POST['Comment'];
            if ($issue->addComment($comment)) {
                Yii::app()->user->setFlash('commentSubmitted', "Your comment has been added.");
                $this->refresh();
            }
        }
        return $comment;
    }

}
